import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token,user=None,request=None):

    '''
    自定义jwt认证返回
    因为当前　的　jwt 只能返回token 我们需要在登陆界面返回　user_id  username
    '''

    return {

        'token':token,
        'user_id':user.id,
        'username':user.username
    }

# 增加用户和手机号都可以作为登陆　修改django 认证系统的后端django.contrip.auth.backends.Modelbackend  并重写　authenticate的方法


def get_user_by_account(account):

    try:
        if re.match(r'1[345789]\d{9}', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        user = None
    return user


class UsernameMobileAuthBackend(ModelBackend):
    '''
    自定义用户名或手机号登陆认证
    '''

    def authenticate(self, request, username=None, password=None, **kwargs):

        user = get_user_by_account(username)

        if user is not None and user.check_password(password):
            return user

